<template>
    <div>
      
            <!-- <van-icon name="scan"  slot="right" /> -->
        <!-- <van-icon name="scan" class="scan-button" slot="right" @click="onscan()" /> -->
        <van-icon name="scan" class="scan-button" slot="left" v-if="showScan" @click="onscan()" />
        <van-icon name="chat-o" class="scan-button2"  @click="goMessage()" />
        <div class="content">
            <div class="menu-list" v-for="(item, index) in menuList" :key="index">
                <template v-if="item.MenuKind != 3 && item.MenuKind != 5 && item.MenuNo.length == 2">
                    <div>
                        <div class="menu-title">
                            {{ item.MenuName }}
                        </div>
                        <div class="menu">
                            <div class="menu-icon" v-for="(item1, index1) in item.children" :key="index1" @click="_openMenu(item1)">
                                <!-- <img :src="require('../../assets/Images/AppIcon/'+item1.url+'.png')" alt="" /> -->
                                <van-badge :content="cnObj[item1.MenuModuleType]" max="99" v-if="cnObj[item1.MenuModuleType] > 0">
                                    <img :src="item1.url" alt="" />
                                </van-badge>
                                <img :src="item1.url" alt="" v-if="!cnObj[item1.MenuModuleType]" />
                                <div class="icon-title">{{ item1.MenuName }}</div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div class="menu-title mb-20">
                <span> 待办事项</span>
                <span style="margin-left: 20px; font-size: 12px">当前还有 <span style="color: red"> {{ totalCount }}</span>个任务</span>
                <span style="float: right; font-size: 14px" @click="goMore()">更多
                    <van-icon name="arrow" />
                </span>
            </div>
            <div class="home-content">
                <van-list style="margin: 5px" :finished="finished" v-model="loading">
                    <div class="plan-list">
                        <div class="plan-detail mb-10" v-for="(item, index) in list" :key="index" @click="_goDetail(item)">
                            <div class="plan-detail-hd mb-10" style="line-height: 20px;">
                                <div>
                                    <span class="circular">
                                        <span class="circular_num" style="">{{ index + 1 }}</span>
                                    </span>
                                </div>

                                <!-- <img
									src="@/assets/Images/AppIcon/icon_studyplan_icon.png"
									alt=""
								/> -->
                                <div class="mt-5">
                                    <div class="plan-detail-title mb-10">{{ item.Title }}</div>
                                    <div class="plan-detail-describe">
                                        {{ item.Content }}
                                    </div>
                                    <div class="plan-detail-describe mt-5">
                                        接收时间： {{ item.CreateDate }}
                                    </div>
                                </div>
                            </div>
                            <div type="warning" class="plan-detail-tag">
                                <van-icon name="arrow" />
                            </div>
                        </div>
                    </div>
                </van-list>
            </div>
        </div>

        <Tabbar :showSnapshot="showSnapshot" />
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getMenuList } from "@/api/sysPhoneMenu.js";
import { getTodoCnt, commonMessagePageData } from "@/api/commonMessage.js";
import { loadWxTicket, loadWxWorkTicket } from "@/utils/Ticket.js";
import Tabbar from "@/components/Tabbar.vue";
import toTree from "@/utils/toTree.js";
import { doMessageClick } from "@/utils/message.js";
import { Toast } from "vant";
import { qrCodeVerify } from "@/api/public.js";
import os from "@/utils/os.js";
import Cookies from 'js-cookie'
import menulist_data from '@/assets/json/menulist.json'
import menulist_data_qy from '@/assets/json/menulist_qy.json'
export default {
    components: {
        Tabbar,
    },
    data() {
        return {
            
            // showSnapshot:
            //     (this.$store.state.companySysType == "AQX" ||
            //         this.$store.state.companySysType == "AJX" ||
            //         this.$store.state.companySysType == "RA" ||
            //         this.$store.state.companySysType == "JG" ||
            //         this.$store.state.companySysType == "JT") && !this.$store.state.isTempUser,
            showSnapshot:this.$store.state.companySysType == "JG"&&!this.$store.state.isTempUser,
            menuList: [],
            url: "",
            list: [],
            cnObj: {},
            finished: true,
            loading: false,
            totalCount: 0,
            filter: {
                page: 0,
                dataType: "TaskList",
                limit: 5,
            },
            showScan: false,
        };
    },
    
    created() {
        if (this.$route.query.navTo) {
            this.$store.commit("setNavTo", this.$route.query.navTo);
        }
        if (this.$route.params.qrcode || this.$route.query.qrcode) {
            var qrCode = this.$route.params.qrcode || this.$route.query.qrcode;
            this.qrCodeVerifyFun(qrCode);
        } else {
            let examResultID = localStorage.getItem("examResultID");
            if (examResultID) {
                this.$router.push("/Train/ExamResult?id=" + examResultID);
                localStorage.removeItem("examResultID");
                return;
            }
            this.getMenuList();
            this.getTodoCnt();
            this.getTodoList();
        }
    },
    mounted() {
        if(this.$route.query.qlt){
            Cookies.set('ASP.NET_SessionId', this.$route.query.qlt)
        }
        
        if (!os.isPC && os.isWxWork) {
            console.log("企业微信客户端");
            this.showScan = true;
            loadWxWorkTicket(["scanQRCode"]);
        } else if (!os.isPC && os.isWx) {
            console.log("微信客户端");
            let arr = ["scanQRCode"];
            this.getSign(arr);
        } else {
            console.log("其他");
            this.getSign(["scanQRCode"]);
        }
        if (this.$store.state.isLogin) {
            var navUrl = "";
            switch (this.$store.state.navTo) {
                case "message":
                    navUrl = "/MoreTodo";
                    break;
                case "warning":
                    navUrl = "/Warning";
                    break;
                default:
                    navUrl = "";
                    break;
            }
            if (navUrl) {
                this.$router.push({
                    path: navUrl,
                });
            }
        }
    },
    watch: {
        "$route.query.num"(to, from) {
            //监听路由是否变化
            if (this.$route.path == "/index") {
                //仅在当前页面生效
                if (to != from) {
                    this.getMenuList();
                    this.getTodoCnt();
                    this.getTodoList();
                }
            }
        },
    },
    computed: {
        ...mapGetters(["userName"]),
    },
    methods: {
        qrCodeVerifyFun(qrCode) {
            qrCodeVerify({ code: qrCode, silence: true })
                .then((r) => {
                    if (r.data.Data) {
                        var retUrl =
                            "/index?num=" + Math.ceil(Math.random() * 100000);
                        var qrEntity = JSON.parse(r.data.Data);
                        switch (r.data.CodeType) {
                            case "ResourcePosition":
                                retUrl = "/PlanEmergencyResourceCheck";
                                this.$router.push({
                                    path: retUrl,
                                    query: {
                                        positionCode: qrEntity.Code,
                                    },
                                });
                                break;
                            case "TrainPlan":
                            case "TrainPlanLevel3Safety":
                                retUrl = "/TrainingDetail";
                                this.$router.push({
                                    path: retUrl,
                                    query: {
                                        PlanCode: qrEntity.Code,
                                        CodeType: r.data.CodeType,
                                    },
                                });
                                break;
                            case "TrainEntrustedPlan":
                                retUrl = "/TrainingEntrustedDetail";
                                this.$router.push({
                                    path: retUrl,
                                    query: {
                                        PlanCode: qrEntity.Code,
                                        CodeType: r.data.CodeType,
                                    },
                                });
                                break;
                            case "RU":
                                retUrl = "/Site_RiskUnit/RiskLocationDetail";
                                this.$router.push({
                                    path: retUrl,
                                    query: { code: qrEntity.Code },
                                });
                                break;
                            case "RA":
                                retUrl = "/Site_RiskUnit/RiskUnitAreaDetail";
                                this.$router.push({
                                    path: retUrl,
                                    query: { code: qrEntity.Code },
                                });
                                break;
                            case "Company":
                                if (!this.$store.state.CompanyCode) {
                                    this.$router.push({
                                        path: "/bindCompany",
                                        query: {
                                            data: r.data.Data,
                                            codeType: r.data.CodeType
                                        }
                                    });
                                }
                                break;
                            case "Equ":
                                retUrl = "/Equipment/Detail";
                                this.$router.push({
                                    path: retUrl,
                                    query: { equipmentCode: qrEntity.Code },
                                });
                                break;
                            case "Chem":
                                retUrl = "/Chemical/Detail";
                                this.$router.push({
                                    path: retUrl,
                                    query: { ChemCode: qrEntity.Code },
                                });
                                break;
                            default:
                                var linkUrl = r.data.RedirectUrl;
                                if (linkUrl) {
                                    if (linkUrl.includes("/h5/#/")) {
                                        linkUrl = linkUrl.substring(6);
                                    }
                                    this.$router.push({
                                        path: linkUrl,
                                    });
                                }
                                else {
                                    //否则打开菜单
                                    this.getMenuList();
                                    this.getTodoCnt();
                                    this.getTodoList();
                                }
                                break;
                        }
                    }
                })
                .catch((err) => {
                    console.log(err);
                    this.$toast("无效的二维码");
                });
        },
        getTodoCnt() {
          
                getTodoCnt()
                .then((res) => {
                    let newObj = {};
                    res.data.map((item, index) => {
                        let newkey = item.TemplateCode;
                        let newValue = item.Cnt;
                        newObj[newkey] = item.Cnt;
                    });
                    this.cnObj = newObj;
                })
                .catch((err) => {
                    console.log("err", err);
                });
            
      
        },
        getTodoList() {
            this.loading = true;
            commonMessagePageData(this.filter).then((res) => {
                this.loading = false;
                if (!res.data.HasNextPage) {
                    this.finished = true;
                }
                this.list = res.data.Data;
                this.totalCount = res.data.TotalCount;
                this.filter.page = res.data.PageIndex;
            });
        },
        getMenuList() {
         
            if(process.env.VUE_APP_PLANTFORM=='QTYJ'){
                let m_data= this.$store.state.CompanyType=='JG'?menulist_data:menulist_data_qy
                m_data.forEach((item)=>{
                    item.url=process.env.VUE_APP_BASE_API + item.Icon;
                    
                })
                this.menuList=toTree(m_data)
            }else{
                getMenuList()
                .then((res) => {
                    res.data.forEach((item) => {
                        item.url = process.env.VUE_APP_BASE_API + item.Icon;
                        if(item.MenuModuleType=='FKCompanyList'){
                            this.$store.state.isFkManager=true
                        }
                    });
                    this.menuList = toTree(res.data);
                })
                .catch((err) => {
                    console.log("err", err);
                });
            }
           
   
        },
        splitFileName(text) {
            var pattern = /\.{1}[a-z]{1,}$/;
            if (pattern.exec(text) !== null) {
                return text.slice(0, pattern.exec(text).index);
            } else {
                return text;
            }
        },
        _goDetail(item) {
            doMessageClick.call(this, item);
        },
        goMore(item) {
            this.$router.push({
                path: "/MoreTodo",
            });
        },
        // 打开菜单
        _openMenu(item) {
            if (item.LinkUrl) {
                var linkUrl = item.LinkUrl;
                if (item.LinkUrl.includes("/h5/#/")) {
                    linkUrl = item.LinkUrl.substring(6);
                }
                this.$router.push("/" + linkUrl);
            } else if (item.MenuModuleType) {
                if (item.MenuModuleType == "help") {
                    this.$router.push({
                        name: "CheckReportDetail3",
                        query: {
                            // http://139.196.18.102:8020//Uploads/00001/Entrusted/0208/b8e0b2134ffa4d4f8a9423c6883dfde2.pdf
                            url: "https://qyb.safetyhua.com/Uploads/10092/20210713/68ae2caf-e97a-4f8b-a304-9300067d0d23.pdf",
                        },
                    });
                } else if (item.MenuModuleType == "Folder") {
                    if (item.MenuName == "目标职责") {
                        this.$router.push({
                            path: "/Folder",
                            query: { List: JSON.stringify(item.children) },
                        });
                    } else if (item.MenuName == "制度化管理") {
                        this.$router.push({
                            path: "/Folder2",
                            query: { List: JSON.stringify(item.children) },
                        });
                    } else if (item.MenuName == "应急预案") {
                        this.$router.push({
                            path: "/Folder3",
                            query: { List: JSON.stringify(item.children) },
                        });
                    } else if (item.MenuName == "职业健康") {
                        this.$router.push({
                            path: "/Folder4",
                            query: { List: JSON.stringify(item.children) },
                        });
                    } else if (item.MenuName == "安全绩效考核") {
                        this.$router.push({
                            path: "/Folder5",
                            query: { List: JSON.stringify(item.children) },
                        });
                    } else if (item.MenuName == "事故管理") {
                        this.$router.push({
                            path: "/Folder6",
                            query: { List: JSON.stringify(item.children) },
                        });
                    } else if (item.MenuName == "应急管理") {
                        this.$router.push({
                            path: "/Folder7",
                            query: { List: JSON.stringify(item.children) },
                        });
                    }else if (item.MenuName == "基本信息") {
                        this.$router.push({
                            path: "/BaseInfo",
                           
                        });
                    }else if (item.MenuName == "隐患排查") {
                        this.$router.push({
                            path: "/Folder8",
                            query: { List: JSON.stringify(item.children) },
                        });
                    }else if (item.MenuName == "安全台账") {
                        this.$router.push({
                            path: "/Folder9",
                            query: { List: JSON.stringify(item.children) },
                        });
                    }else if (item.MenuName == "信息中心") {
                        this.$router.push({
                            path: "/CommonInfo",
                            
                        });
                    }
                    else if (item.MenuName == "教育培训") {
                        this.$router.push({
                            path: "/Folder10",
                            query: { List: JSON.stringify(item.children) },
                        });
                    }
                } else {
                    this.$router.push("/" + item.MenuModuleType);
                    return;
                }
            }
        },

        onscan() {
            wx.invoke(
                "scanQRCode",
                {
                    desc: "scanQRCode desc",
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                },
                (res) => {
                    if (res.err_msg == "scanQRCode:ok") {
                        if (res.resultStr) {
                            let qrCode = os.isAndroid
                                ? res.resultStr
                                : os.isPhone
                                    ? JSON.parse(res.resultStr).scan_code
                                        .scan_result
                                    : "";
                            this.qrCodeVerifyFun(qrCode);
                        }
                    }
                }
            );
        },
        goMessage(){
            this.$router.push("/message");
        },
        getSign(arr) {
            let params = {
                url: window.location.href.split("#")[0],
            };
            this.$axios
                .get("/WxOpen/GetSignature", { params: params })
                .then((res) => {
                    console.log("调用成功");
                    this.showScan = true;
                    wx.config({
                        beta: true,
                        debug: false,
                        appId: res.data.appId,
                        timestamp: res.data.timestamp,
                        nonceStr: res.data.nonceStr,
                        signature: res.data.signature,
                        jsApiList: arr,
                    });
                    wx.ready(() => {
                        wx.checkJsApi({
                            jsApiList: arr,
                            success: function (res) {
                                arr.forEach((a) => {
                                    console.log("调用JS方法[" + a + "]的微信tick成功！" + JSON.stringify(res))
                                });
                            },
                        });
                    });
                    wx.error((err) => {
                        console.log("错误" + err);
                    });
                })
        }
    },
};
</script>

<style lang="less" scoped>
.scan-button {
    position: fixed;
    top: 15px;
    left: 20px;
    color: #fff;
    font-size: 16px;
    z-index: 99999;
}
.scan-button2 {
    position: fixed;
    top: 15px;
    right: 20px;
    color: #fff;
    font-size: 16px;
    z-index: 99999;
}
.content {
    padding-top: 20px;
    background: #fff;
}
.menu {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    border-bottom: 1px solid #eee;
    margin: 10px 0;
    margin-bottom: 20px;
    .menu-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 25%;
        font-size: 12px;
        margin-bottom: 15px;
        img {
            width: 50px;
            height: 50px;
            margin-bottom: 10px;
            border-radius: 50%;
        }
    }
}

.circular {
    border-radius: 50%;
    height: 50px;
    width: 50px;
    margin-top: 10px;
    margin-right: 5px;
    display: inline-block;
    background: #57beda;
    .circular_num {
        display: block;
        color: #ffffff;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }
    //   vertical-align: top;
}

.home-content {
    //background-color: #f5f5f5;
    padding-bottom: 50px;
    .info_search {
        padding: 10px;
        border-radius: 5px !important;
        .van-field__control {
            background-color: #ffffff !important;
        }
    }
}

.plan-detail {
    width: 100%;
    background-color: #f5f5f5;
    border-radius: 8px;
    padding: 10px;
    color: #333;
    font-size: 10px;
    position: relative;
    .plan-detail-tag {
        position: absolute;
        top: 40%;
        right: 10px;
    }
}

.plan-detail-hd {
    display: flex;
    img {
        width: 50px;
        height: 50px;
        margin-right: 10px;
    }
    .plan-detail-title {
        font-size: 14px;
        color: #333;
    }
    span {
        color: #666;
    }
}
.plan-detail-describe {
    width: 90%;
    font-size: 12px;
    line-height: 1.2;
    // word-break: break-all;
    text-overflow: ellipsis;
    color: #666;
    display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/
    -webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/
    -webkit-line-clamp: 2; /** 显示的行数 **/
    overflow: hidden; /** 隐藏超出的内容 **/
    word-break: break-all;
}
.plan-detail-bd {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>
